package com.fcl.blog.config.interceptor;


import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.fcl.blog.exception.ServiceException;
import com.fcl.blog.po.Admin;
import com.fcl.blog.po.User;
import com.fcl.blog.service.UserServie;

import com.fcl.blog.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @Author 付
 * @Date 2023/10/12 14:10
 * @Version 1.0
 * @description
 * @since 1.0
 */

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final String ERROR_CODE="401";

    @Autowired
    private UserServie userService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("header to token==="+request.getHeader("token"));
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw  new ServiceException(ERROR_CODE,"token验证失败，请重新登录");
        }
        //获取token中的user id
        String username;
        String password;
        try {
            Claims claims = TokenUtil.decodeToken(token);
            username = (String) claims.get("username");
            password = (String) claims.get("password");
        }catch (JWTDecodeException j){
            throw  new ServiceException(ERROR_CODE,"token验证失败，请重新登录");
        }

        // 根据token中的Userid查询数据库
//        User user = userService.selectByUsernameAndPasswordToUser(Long.valueOf(userId));
        Admin admin = userService.selectByUsernameAndPassword(username, password);
        System.out.println("admin"+admin);
//        User user = new User();
        if (admin == null){
            User user1 = userService.selectByUsernameAndPasswordToUser(username, password);
            System.out.println("user1"+user1);
            if (user1==null){
                throw  new ServiceException(ERROR_CODE,"token验证失败，请重新登录1");
            }
            throw  new ServiceException(ERROR_CODE,"token验证失败，请重新登录2");
        }

        // 用户密码加签验证token
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
//        try {
//            jwtVerifier.verify(token);// 验证token
//        }catch (JWTVerificationException j){
//            throw  new ServiceException(ERROR_CODE,"token验证失败，请重新登录");
//        }
        return true;
    }
}
